package org.demo.szml.userservice.config;


import lombok.extern.slf4j.Slf4j;
import org.demo.szml.api.exception.ApiInvokeBaseException;
import org.demo.szml.api.response.Response;
import org.demo.szml.api.response.ResponseCode;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Objects;

/**
 * @description: 用户服务全局异常处理器
 * @date: 2025/6/19 16:27
 * @version: 1.0
 */
@Slf4j
@RestControllerAdvice
public class UserGlobalExceptionHandler {

    /** 处理API调用时可能的异常
     * @param e 异常信息
     * @return 响应结果
     */
    @ExceptionHandler(value = ApiInvokeBaseException.class)
    public Response<Void> handleBaseException(ApiInvokeBaseException e){
        log.error("出现异常:{},信息为:{}",e.getClass().getName(),e.getMessage());
        //如果存在错误提示，则返回错误提示，否则返回未知错误 交由前端进行错误信息显示
        if(Objects.isNull(e.getShowErrorPrompt())){
            return Response.<Void>builder().code(ResponseCode.UNKNOWN_FAILED).build();
        }
        return Response.<Void>builder().code(ResponseCode.REASON_FAILED).info(e.getShowErrorPrompt()).build();
    }

    /** 其他任意类型没有被捕获而抛出 则返回未知错误
     * @param e 异常信息
     * @return 响应结果
     */
    @ExceptionHandler(value = Exception.class)
    public Response<Void> handleException(Exception e){
        log.error("出现异常:{},信息为:{}",e.getClass().getName(),e.getMessage());
        return Response.<Void>builder().code(ResponseCode.UNKNOWN_FAILED).build();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("出现异常:{},信息为:{}",e.getClass().getName(),e.getMessage());
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        if(ObjectUtils.isEmpty(allErrors)){
            return Response.<Void>builder().code(ResponseCode.REASON_FAILED).info("参数错误").build();
        }
        StringBuilder errorInfo = new StringBuilder();
        errorInfo.append("信息不符合要求:");
        for (ObjectError allError : allErrors) {
            errorInfo.append(allError.getDefaultMessage()).append(",");
        }
        errorInfo.append("。");
        return Response.<Void>builder().code(ResponseCode.REASON_FAILED).info(errorInfo.toString()).build();
    }


}
